package cn.tedu.mvccoolshark.controller;

import cn.tedu.mvccoolshark.mapper.ProductMapper;
import cn.tedu.mvccoolshark.pojo.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

// 注解作用于类上，作用就是将类中的方法返回值直接作为HTTP响应的内容。在控制器类中加入该注解后，无需在每个方法上添加`@ResponseBody`注解
@RestController
@RequestMapping("/v1/product/")
public class ProductController {
    // 1.自动装配
    //   required=false参数，表示装配不成功也无所谓
    @Autowired(required = false)
    private ProductMapper productMapper;

    /**添加商品*/
    @RequestMapping("insert")
    public String insertProduct(Product product){
        System.out.println("product = " + product);
        // 2.调用接口方法实现数据插入
        productMapper.insert(product);

        return "添加成功";
    }

    /**商品列表*/
    @RequestMapping("select")
    public String selectProduct(){
        List<Product> list = productMapper.select();

        // 1.定义html字符串
        String html = "<table border='1'>";
        html += "<caption>商品列表</caption>";
        html += "<tr><th>id</th><th>标题</th><th>价格</th><th>库存</th><th>操作</th></tr>";

        // 2.使用foreach遍历每个商品对象，并将其添加到html标签中
        for (Product p: list) {
            html += "<tr>";
            html += "<td>" + p.getId() + "</td>";
            html += "<td>" + p.getTitle() + "</td>";
            html += "<td>" + p.getPrice() + "</td>";
            html += "<td>" + p.getNum() + "</td>";
            // http://localhost:8080/delete?id=xxx
            html += "<td><a href='/v1/product/delete?id=" + p.getId() + "'>删除</a>" + "</td>";
            html += "</tr>";
        }

        html += "</table>";

        // 3.返回html字符串
        return html;
    }

    /**删除商品*/
    @RequestMapping("delete")
    public String deleteProduct(int id){
        // 调用接口方法
        productMapper.delete(id);
        return "删除成功";
    }

    /**修改商品*/
    @RequestMapping("update")
    public String updateProduct(Product product){
        productMapper.update(product);

        return "修改成功";
    }
}









